package com.quanquan.store.service;

import DTO.PageDTO;
import com.quanquan.store.configBean.RabbitSender;
import com.quanquan.store.dto.LabelDTO;
import com.quanquan.store.entity.Label;
import com.quanquan.store.entity.StoreLabel;
import com.quanquan.store.repository.LabelRepository;
import com.quanquan.store.repository.StoreLabelRepository;
import com.quanquan.store.request.StoreLabelRequest;
import commond.ImageOutPut;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import utils.DateUtils;
import utils.UUIDGenerator;

import java.util.*;

/**
 * @ClassName:LabelService
 * @Description:TODO
 * @Author:xiongjunbao
 * @Date:2019/7/19 13:58
 * @Version 1.0
 */
@Service
public class LabelService {

    private final StoreLabelRepository storeLabelRepository;
    private final LabelRepository labelRepository;
    private final RabbitSender rabbitSender;

    @Autowired
    public LabelService(LabelRepository labelRepository, RabbitSender rabbitSender, StoreLabelRepository storeLabelRepository) {
        this.labelRepository = labelRepository;
        this.rabbitSender = rabbitSender;
        this.storeLabelRepository = storeLabelRepository;
    }

    /**
     * 新增楼层信息（后台）
     *
     * @param request
     * @return
     */
    public boolean saveLabel(StoreLabelRequest request) {
        System.out.println(request);
        Date date = new Date();
        Label label = new Label();
        label.setId(UUIDGenerator.getUUID());
        label.setCreateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
        label.setUpdateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
        label.setSortOrder(request.getSortOrder());
        label.setStatusRemove(0);
        label.setStatusShow(request.getStatusShow());
//        floor.setFloor(request.getFloor());
        label.setLabelName(request.getLabelName());
        label.setLabelImage(request.getLabelImage());
        label.setImageId(request.getImageId());
        label.setLabelPicture(request.getLabelPicture());
        label.setPictureId(request.getPictureId());
        labelRepository.saveAndFlush(label);
        List<String> imageIds = new LinkedList<>();
        imageIds.add(request.getImageId());
        imageIds.add(request.getPictureId());
        bandingImageShip(label.getId(), imageIds);
        return true;
    }

    /**
     * 绑定标签图片
     *
     * @param labelId
     * @param imageIdlist
     */
    private void bandingImageShip(String labelId, List<String> imageIdlist) {
        ImageOutPut imageOutPut = new ImageOutPut();
        imageOutPut.setForeignKeyId(labelId);
        imageOutPut.setImageSource("label");

        Map<String, Object> properties = new HashMap<>();
        properties.put("imageIds", imageIdlist);

        String exchange = "image.exchange";
        String routingKey = "image.label";

        rabbitSender.sendMessageToMQ(imageOutPut, properties, exchange, routingKey);
    }

    /**
     * 后台用商户标签列表（后台）
     *
     * @param requestBody
     * @return
     */
    public PageDTO<Label> allLabelManagement(StoreLabelRequest requestBody) {
        Integer size = requestBody.getSize();
        Integer page = requestBody.getPage();
        Sort sort = new Sort(Sort.Direction.ASC, "sortOrder");
        Pageable pageable = PageRequest.of(page, size, sort);
        Label label = new Label();
        //设置floor的参数
        label.setStatusRemove(0);
        Example<Label> example = Example.of(label);
        Page<Label> findAll = labelRepository.findAll(example, pageable);
        PageDTO<Label> pageDTO = new PageDTO<>();
        pageDTO.setTotal(findAll.getTotalElements());
        pageDTO.setList(findAll.getContent());
        pageDTO.setTotalPage(findAll.getTotalPages());
        pageDTO.setPage(page);
        pageDTO.setPageSize(size);
        return pageDTO;
    }

    /**
     * 后台用商户标签列表（后台）
     *
     * @param requestBody
     * @return
     */
    public PageDTO<Label> noDisLabelManagement(StoreLabelRequest requestBody) {
        Integer size = requestBody.getSize();
        Integer page = requestBody.getPage();
        Sort sort = new Sort(Sort.Direction.ASC, "sortOrder");
        Pageable pageable = PageRequest.of(page, size, sort);
        Label label = new Label();
        //设置floor的参数
        label.setStatusRemove(0);
        label.setStatusShow(0);
        Example<Label> example = Example.of(label);
        Page<Label> findAll = labelRepository.findAll(example, pageable);
        PageDTO<Label> pageDTO = new PageDTO<>();
        pageDTO.setTotal(findAll.getTotalElements());
        pageDTO.setList(findAll.getContent());
        pageDTO.setTotalPage(findAll.getTotalPages());
        pageDTO.setPage(page);
        pageDTO.setPageSize(size);
        return pageDTO;
    }


    /**
     * 根据id查看商户标签信息（后台）
     *
     * @param request
     * @return
     */
    public LabelDTO query(StoreLabelRequest request) {
        System.out.println("进来了" + request.getLabelId());
        Label label = labelRepository.findbyLabelId(request.getLabelId());
        LabelDTO labelDTO = new LabelDTO();
        //通过映射关系来赋值 //TODO 断点看一下
        BeanUtils.copyProperties(label, labelDTO);
        return labelDTO;
    }

    /**
     * 更新标签信息
     *
     * @param request
     * @return
     */
    public boolean updateStoreLabel(StoreLabelRequest request) {
        Date date = new Date();
        Label label = labelRepository.findbyLabelId(request.getLabelId());
        if (label == null) {
            return false;
        }
        label.setUpdateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
        label.setSortOrder(request.getSortOrder());
        label.setStatusRemove(0);
        label.setStatusShow(request.getStatusShow());
        label.setLabelName(request.getLabelName());
        label.setLabelImage(request.getLabelImage());
        label.setImageId(request.getImageId());
        label.setLabelPicture(request.getLabelPicture());
        label.setPictureId(request.getPictureId());
        List<String> imageIds = new LinkedList<>();
        imageIds.add(request.getImageId());
        bandingImageShip(label.getId(), imageIds);
        //如果隐藏标签，将绑定的关系也去除
        if (request.getStatusShow() == 1) {
            List<StoreLabel> storeLabels = storeLabelRepository.findByLabelId(label.getId());
            for (StoreLabel storeLabel : storeLabels) {
                storeLabel.setStatusRemove(1);
                storeLabel.setUpdateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
                storeLabelRepository.saveAndFlush(storeLabel);
            }
        }
        labelRepository.saveAndFlush(label);

        return true;
    }

    /**
     * 删除标签
     *
     * @param request
     * @return
     */
    public boolean deleteLabel(StoreLabelRequest request) {
        Date date = new Date();
        Label label = labelRepository.findbyLabelId(request.getLabelId());
        if (label == null) {
            return false;
        }
        label.setUpdateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
        label.setStatusRemove(1);
        //同时删除关系
        List<StoreLabel> storeLabels = storeLabelRepository.findByLabelId(label.getId());
        for (StoreLabel storeLabel : storeLabels) {
            storeLabel.setStatusRemove(1);
            storeLabel.setUpdateTime(DateUtils.dateToString(date, DateUtils.TIMESTAMP));
            storeLabelRepository.saveAndFlush(storeLabel);
        }
        labelRepository.saveAndFlush(label);
        return true;
    }


    /**
     * 前端使用查询所有有效的商铺标签
     *
     * @param request
     * @return
     */
    public List<Object> findAllLabel(StoreLabelRequest request) {
        Integer page = request.getPage() == null ? 0 : request.getPage();
        Integer size = request.getSize() == null ? 100 : request.getSize();
        List<Object> objectList = new LinkedList<>();
        List<Label> labels = labelRepository.findAllLabel(page * size, size);
        for (Label label : labels) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", label.getId());
            map.put("labelName", label.getLabelName());
            map.put("labelImage", label.getLabelImage());
            map.put("labelPicture", label.getLabelPicture());
            objectList.add(map);
        }
        return objectList;
    }

}
